﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vote.Business;
using Vote.DataEntity;
using Vote.Web.Common;
using System.Web.Security;
using Newtonsoft.Json;

namespace Vote.Web.Controllers
{
    [Authorization]
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ViewResult EditAdmin()
        {
            AdminUserDataEntity entity = new AdminUserDataEntity();

            if (Request.Cookies[ConfigUtility.AdminSessionKey] != null)
            {
                entity = JsonConvert.DeserializeObject<AdminUserDataEntity>(Request.Cookies[ConfigUtility.AdminSessionKey].Value);
            }
            ViewBag.Id = entity.Id;
            ViewBag.userName = entity.Username;
            return View();
        }


        public JsonResult Editadminuser(AdminUserDataEntity admin)
        {
            admin.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(admin.Password, "MD5");
            Boolean result = AdminUserModel.Instance.EditAdminuser(admin);
            if (result)
            {
                //this.HttpContext.Session[ConfigUtility.AdminSessionKey] = admin;
                Response.Cookies[ConfigUtility.AdminSessionKey].Value = JsonConvert.SerializeObject(admin);
                Response.Cookies[ConfigUtility.AdminSessionKey].Expires = DateTime.Now.AddHours(12);
            }
            return new JsonResult() { Data = new { RetCode = result } };
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [AllowAnonymousAttribute]
        public ActionResult Signin()
        {
            return View();
        }

        /// <summary>
        /// 验证登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        [AllowAnonymousAttribute]
        public JsonResult AuthUser(String userName, String passWord)
        {
            passWord = FormsAuthentication.HashPasswordForStoringInConfigFile(passWord, "MD5");
            AdminUserDataEntity result = AdminUserModel.Instance.Login(userName, passWord);

            if (result.Id > 0)
            {
                Response.Cookies[ConfigUtility.AdminSessionKey].Value = JsonConvert.SerializeObject(result);
                Response.Cookies[ConfigUtility.AdminSessionKey].Expires = DateTime.Now.AddHours(12);
            }

            return new JsonResult() { Data = new { RetCode = result.Id } };
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [AllowAnonymousAttribute]
        public JsonResult Logout()
        {
            Session.Remove(ConfigUtility.AdminSessionKey);
            return new JsonResult() { Data = new { RetCode = true } };
        }
    }
}
